// packageA/pages/goodsStorageIn/goodsStorageIn.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({
  /**
   * 页面的初始数据
   */
  data: {  
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,   
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '待入库', value: 0},
      {text: '已入库', value: 1}
    ],
    valueState: 0,
    //仓库选择框
    showStorage:false,
    //仓库选择数据
    storageList:[],
    //仓库id
    storageId:null,
    //仓库名称
    storageName:'请选择仓库',
    //当前登录用户
    user: null,
    //搜索词
    searchValue:'',
    //项级部门信息
    companyInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    this.setData({ 
      user: user
    })

    if(user.departObj[0].isProject){
      //获取顶级部门信息，然后判断是否创建仓库
      this.getCompanyInfo();
    }

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj = {
      selectFields: ['id','storage','state','orderNo','staff','inStorageTime','goodsList','remark','dataAuthority'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    //查询单号
    if(this.data.searchValue){
      dataObj.orderNo='%' +this.data.searchValue+ '%';
    }

    //查询仓库
    if(this.data.storageId){
      dataObj['storage.id']=this.data.storageId;
    }
    
    //筛选状态
    if(this.data.valueState!=-1){
      dataObj.state=this.data.valueState;
    }

    let param = {
      isAuth: true,
      className: 'requisitionInStorage',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('入库单列表');
        console.log(result);

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.self_state='待入库';
              item.self_class='c-1';
              break;
            case 1:
              item.self_state='已入库';
              item.self_class='c-2';
              break;
          } 
          
          //物资名称         
          if(item.goodsList){
            let arr=item.goodsList;
            let names=[];
            for(let i=0;i<arr.length;i++){
              names.push(arr[i].goods.name);
            }
            item.self_names=names
          }
        });

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //跳转添加/编辑
  goToAdd({currentTarget}){
    let obj={}

    if(currentTarget.dataset.detail){
      let detail=currentTarget.dataset.detail;
      obj.id=detail.id;
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsStorageInAdd/goodsStorageInAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '单据删除后，将无法恢复, 是否继续？',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"requisitionInStorage",
        data:{
          id: detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          setTimeout(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
  },

  //显示仓库
  onShowStorage(){
    this.setData({
			showStorage: true
    })
    this.getStorageList();
  },

  //查询仓库
  getStorageList(){
    this.setData({
      storageList: []
    })

    let param = {
      isAuth: true,
      className: 'clientStorage',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchStorage){
      param.data.name='%' + this.data.valueSearchStorage + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];

        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id
          });
        });

        this.setData({
          storageList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏仓库
  onCloseStorage(){
    this.setData({
      showStorage: false,
      valueSearchStorage:''
    })
  },

  //确认仓库
  onConfirmStorage(e){
    this.setData({
      storageId: e.detail.value.id,
      storageName: e.detail.value.text
    })
    this.onCloseStorage();
    this.refreshListAndPage();
  },

  //搜索仓库
  onChangeStorageVal(e){
    this.setData({
      valueSearchStorage: e.detail
    })
    this.getStorageList();
  },

  //清除仓库
  onCancelStorage(){
    this.setData({
      storageId: null,
      storageName: '请选择仓库'
    })
    this.onCloseStorage();
    this.refreshListAndPage();
  },

  //跳转详情
  goToDetail({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsStorageInDetail/goodsStorageInDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //获取顶级部门信息
  getCompanyInfo(){
    let user=app.globalData.userInfo;

    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        id: user.depart,
        selectFields: ['id','name','company']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];

        if(result.company && result.company.length){
          let company=result.company[0];

          this.setData({
            companyInfo: {
              id: company.id,
              name: company.name
            }
          })

          //查询当前项目的仓库，没有的创建
          this.initStorage();
        }
      }
    }).catch((error) => {
    })
  },

  //查询当前项目的仓库，没有的创建
  initStorage(){
    let user=this.data.user;

    //权限
    let authArr=[user.depart, user.departObj[0].companyId, user.departObj[0].regionId, 1,1938];
    authArr=util.arrayRepeatEmpty(authArr);

    let param={
      manager: {
        id: user.id,
        name: user.userName,
      },
      project: {
        id: user.depart,
        name: user.departName
      },
      depart: {
        id: this.data.companyInfo.id,
        name: this.data.companyInfo.name
      },
      dataAuthority: {
        depart: authArr
      }
    }

    CommonService.findStorage(param).then(res=>{
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})